package redgo

import (
	"github.com/garyburd/redigo/redis"
	"time"
	"until/yml"
	"encoding/json"
	"github.com/kataras/iris/core/errors"
	"until/logger"
)

var RedisPool *redis.Pool

func StartRp()  {
	RedisPool=&redis.Pool{
		// 从配置文件获取maxidle以及maxactive，取不到则用后面的默认值
		MaxIdle:     100,
		MaxActive:   100,
		IdleTimeout: 180 * time.Second,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", yml.Config.Redis)
			if err != nil {
				return nil, err
			}
			// 选择db
			//c.Do("SELECT", REDIS_DB)
			return c, nil
		},
	}
}
func GetOne() redis.Conn {
	if RedisPool!=nil {
		return RedisPool.Get()
	}
	panic("no redispool")
	return nil

}
func GetOneZero() redis.Conn {
	if RedisPool!=nil {
		c:=RedisPool.Get()
		c.Do("SELECT",0)
		return c
	}
	panic("no redispool")
	return nil

}
func GetById(id int) redis.Conn {
	if RedisPool!=nil {
		c:=RedisPool.Get()
		c.Do("SELECT",id)
		return c
	}
	panic("no redispool")
	return nil

}
//获得json
func GetJson(ret interface{},zd string,c redis.Conn,del int) error{
	bs,_:=redis.Bytes(c.Do("GET",zd))
	if bs!=nil {
		err:=json.Unmarshal(bs,ret)
		if err!=nil&&del==1 {
			c.Do("DEL",zd)
		}
		return err
	}
	return errors.New("没有数据")

}
//保存json
func SaveJson(ret interface{},zd string,c redis.Conn) ( interface{},error){
	bannerstr,err:=json.Marshal(ret)
	if err!=nil {
		return nil,err
	}
	replay,err:=c.Do("SET",zd,bannerstr)
	return replay,err
}

//保存hash json
func SaveHashJson(ret interface{},zd string,key string,c redis.Conn) ( interface{},error){
	str,err:=json.Marshal(ret)
	if err!=nil {
		return nil,err
	}
	replay, err := c.Do("HSET", zd,key,str);
	return replay,err
}
//获得hash json
func GetHashJson(ret interface{},zd string,key string,c redis.Conn,del int) error{
	bs,_:=redis.Bytes(c.Do("HGET",zd,key))
	if bs!=nil {
		err:=json.Unmarshal(bs,ret)
		if err!=nil&&del==1 {
			c.Do("DEL",zd)
		}
		return err
	}
	return errors.New("没有数据")
}
func Do(s func(c redis.Conn)) error {
	one:=GetOne()
	defer func() {
		one.Close()
		if err:=recover();err!=nil{
			logger.Error(err.(error).Error())
		}
	}()
	s(one)
	return nil
}